package com.woniuxy.java102vuecli.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.java102vuecli.controller.ResponseResult;
import com.woniuxy.java102vuecli.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author author
 * @Create 2023-09-21 11:34
 */
@Slf4j
@Component
public class LoginInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor");
        //对OPTIONS请求放行

        if(request.getMethod().equals("OPTIONS")){
            log.info("OPTIONS请求，放行");
            return true;
        }
        response.setContentType("text/html;charset=utf-8");
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)&& JwtUtil.validate(token)){
            log.info("token有效，验证是否过期");
            if(!JwtUtil.isExpire(token)){
                log.info("token没有过期，放行，重新生成token");
                //重新生成token
                token = JwtUtil.createToken(JwtUtil.getEid(token), JwtUtil.getEname(token));
                //token存储请求头
                response.setHeader("token", token);
                //前后端分离程序，后端必须暴露响应头，前端才能获取
                response.setHeader("Access-Control-Expose-Headers", "token");
                return true;
            }else{
                log.info("token已经过期，拦截");
                ResponseResult<String> responseResult=new ResponseResult<>(401,"error","token已经过期，拦截");
                response.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
                return false;
            }
        }else{
            log.info("token无效，拦截");
            ResponseResult<String> responseResult=new ResponseResult<>(401,"error","未登录");
            response.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
            return false;
        }

    }
}
